package org.test.web;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.test.model.Article;
import org.test.service.ServiceOne;


/**
 * 请求重定向 ：return "redirect: controllerName"		//url改变
 * 若想传递参数，有两种方式:1拼接URL, 2将参数放入session 到jsp拿到后 立刻删除
 * 
 * 请求转发 ：return "forward: controllerName"		//url 不变
 * @author Guodeqi
 *
 */
@Controller
@RequestMapping("/common")
public class CommonController {
	
	@Autowired
	private ServiceOne service = null;
	
	@RequestMapping("/getArticle")
	public String showArticle(Model model){
		System.out.println("this is CommonController's showArticle()---");
		List<Article> article = service.getArticle();
		model.addAttribute("articles", article);
		return "ShowArticle";
	}
	
	@RequestMapping(value="/getInfo",method={RequestMethod.POST,RequestMethod.GET})
	public String showInfo(String username,String password,MultipartFile uploadFile,Model model){
		System.out.println("---------this is CommonController's showInfo------");
		System.out.println(username+"|--------------|"+password);
		
		model.addAttribute("username", username);
		model.addAttribute("password", password);
		
		try {
			saveImg("new.txt",uploadFile);
			model.addAttribute("uploadResult", "success");
		} catch (Exception e) {
			model.addAttribute("uploadResult", "failed");
		}
		
		return "ShowInfo";
		
	}
	
	@RequestMapping(value="/getInfo2",method={RequestMethod.POST,RequestMethod.GET})
	public String showInfo2(HttpServletRequest request, HttpServletResponse response,Model model){
		
		System.out.println("---------this is CommonController's showInfo2------");
		System.out.println(request+"|--------------|"+response);
		model.addAttribute("username", request.getParameter("username"));
		model.addAttribute("password", request.getParameter("password"));
		
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile uploadFile = multipartRequest.getFile("uploadFile");
			
			String realPath = request.getSession().getServletContext().getRealPath("/upload/")+File.separator;
			saveImg(realPath+"new.txt",uploadFile);
			model.addAttribute("uploadResult", "success");
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("uploadResult", "failed");
		}
		
		return "ShowInfo";
	}
	
	/**
	 * 使用 J2EE api 实现文件下载
	 * @param req
	 * @param resp
	 */
	@RequestMapping(value = "/download1")
	public void downLoad1(HttpServletRequest req,HttpServletResponse resp) {
		OutputStream os = null;
		try {
			os = resp.getOutputStream();
			resp.reset();
			resp.setHeader("Content-Disposition", "attachment; filename=new.txt");
			resp.setContentType("application/octet-stream; charset=utf-8");
			os.write(FileUtils.readFileToByteArray(getDictionaryFile(req)));
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * spring 内置的 文件下载 API
	 * @param req
	 * @return
	 * @throws IOException
	 */
    @RequestMapping("download2")
    public ResponseEntity<byte[]> download(HttpServletRequest req) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "dict.txt");
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(getDictionaryFile(req)),headers, HttpStatus.CREATED);
    }
	
	private File getDictionaryFile(HttpServletRequest req) {
		String dirName = req.getSession().getServletContext().getRealPath("/upload")+File.separator;
		String fileName = "new.txt";
		return new File(dirName+fileName);
	}
	
	private void saveImg(String fileName ,MultipartFile uploadFile) throws IOException{
		
		File f = new File(fileName);
		String absolutePath = f.getAbsolutePath();
		
		FileUtils.writeByteArrayToFile(f, uploadFile.getBytes());
		System.out.println("文件已上传到如下位置"+absolutePath);
	}

	public ServiceOne getService() {
		return service;
	}

	public void setService(ServiceOne service) {
		this.service = service;
	}
	
}
